package com.example.util;

import com.alibaba.fastjson.JSONObject;
import com.example.model.UserMoneyRecord;
import com.example.service.UserMoneyRecordService;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
public class MQConsumeMsgListenerProcessor implements MessageListenerConcurrently {


    @Autowired
    UserMoneyRecordService userMoneyRecordService;

    /**
     * user服务启动的时候, 消费者会建立长链接对消息进行监听，并获取对应主题的消息进行消费。
     * @param list
     * @param consumeConcurrentlyContext
     * @return
     */
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        MessageExt messageExt = list.get(0);
        String aa = "处理成功";
        if ("处理成功".equals(aa)) {

        }
        System.out.printf("%s user服务接受到消息: %s %n", Thread.currentThread().getName(), new String(messageExt.getBody()).toString());
        JSONObject jsonObject = JSONObject.parseObject(new String(messageExt.getBody()));
        Double moneyPaid = Double.valueOf(jsonObject.get("moneyPaid").toString());
        UserMoneyRecord userMoneyRecord = createMoneyRecord(jsonObject);
        System.out.printf("个人支付：%s %n", moneyPaid);
        userMoneyRecordService.insert(userMoneyRecord);
        //todo  获取到订单信息后，做数据筛选，并压缩客户钱包（juc） 以安全同步的方式放入数据
        Map<String, Date> stringDateMap = Collections.synchronizedMap(new HashMap<String, Date>());
//        stringDateMap.get();
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    private UserMoneyRecord createMoneyRecord(JSONObject jsonObject) {
        UserMoneyRecord userMoneyRecord = new UserMoneyRecord();
        Random random = new Random();
        userMoneyRecord.setRecordId(Long.valueOf(random.nextInt(50000)));
        userMoneyRecord.setUserId(jsonObject.get("userId").toString());
        userMoneyRecord.setOrderId(Long.valueOf(jsonObject.get("orderId").toString()));
        userMoneyRecord.setMoneyLogType(1);
        userMoneyRecord.setUseMoney(Double.valueOf(jsonObject.get("moneyPaid").toString()));
        userMoneyRecord.setCreateTime(new Date());
        return userMoneyRecord;
    }
}
